import React, { useState, useRef, useEffect } from "react";
import "../style/Chat.css";

import { useNavigate } from "react-router-dom";

import { NavBar } from "react-vant";

// 路由接参
import { useSearchParams } from "react-router-dom";

import Chatlist from "./Chatlist";

function Chat() {
  const navigate = useNavigate();

  const [useSearch] = useSearchParams();
  let name = useSearch.get("name");

  const ws = useRef(null);
  const [messages, setMessages] = useState([]);
  const chatContainerRef = useRef(null);
  const [text, setText] = useState(""); // 输入框内容

  useEffect(() => {
    // 创建WebSocket连接
    ws.current = new WebSocket("ws://localhost:3005");

    // 当WebSocket连接成功时，发送一条消息
    // ws.onopen = () => {
    //   ws.send(
    //     JSON.stringify({ type: "message", content: "Hello, WebSocket!" })
    //   );
    // };

    // 当收到服务器消息时，更新messages状态
    ws.current.onmessage = (event) => {
      console.log("WebSocket收到消息", event.data);
      setMessages(JSON.parse(event.data));
    };
    // 当WebSocket连接关闭时，执行清理操作
    ws.current.onclose = () => {
      console.log("WebSocket连接已关闭");
    };
    // 当WebSocket发生错误时，执行错误处理
    ws.current.onerror = (error) => {
      console.error("WebSocket错误", error);
    };
    // 清理函数，当组件卸载时断开WebSocket连接
    return () => {
      ws.current.close();
    };
  }, []);

  useEffect(() => {
    if (chatContainerRef.current) {
      chatContainerRef.current.scrollTop =
        chatContainerRef.current.scrollHeight;
    }
  }, [messages]);

  // 发送消息
  const onSend = (event) => {
    event.preventDefault();
    if (text.trim() === "") {
      console.log("请输入内容");
      return;
    }
    let message = {
      type: "seller",
      content: text,
      user: "默林石墨粉肠早餐店",
      uid: "67b32c3cedea12b8121831e0",
      tid: "67b32bfbedea12b8121831de",
      chat_img:
        "https://cdn8.axureshop.com/demo2024/1525603/images/%E9%A6%96%E9%A1%B5/u852.svg",
    };
    ws.current.send(JSON.stringify(message));
    setText("");
  };

  return (
    <div>
      <NavBar title={name} onClickLeft={() => navigate(-1)} />

      <main className="chat-container" ref={chatContainerRef}>
        <Chatlist messages={messages} />
      </main>
      <div
        style={{
          height: "50px",
          position: "fixed",
          bottom: "0",
          left: "0",
          right: "0",
          display: "flex",
          paddingTop: "10px",
          backgroundColor: "white",
          boxShadow: "0 -2px 4px rgba(0, 0, 0, .1)",
        }}
      >
        <input
          type="text"
          className="input-message"
          value={text}
          onChange={(e) => setText(e.target.value)}
        />
        {/* 按下回车键或点击发送按钮发送消息 */}
        <button className="btn-primary" onClick={(event) => onSend(event)}>
          发送
        </button>
      </div>
    </div>
  );
}

export default Chat;
